import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_study_test/app/page/home_item_main.dart';


/**
 * 有状态StatefulWidget
 *  继承于 StatefulWidget，通过 State 的 build 方法去构建控件
 */
class DemoRefreshListView extends StatefulWidget {
  ////通过构造方法传值
  DemoRefreshListView();
  //主要是负责创建state
  @override
  _DemoStateWidgetState createState() => _DemoStateWidgetState();
}

/**
 * 在 State 中,可以动态改变数据
 * 在 setState 之后，改变的数据会触发 Widget 重新构建刷新
 */
class _DemoStateWidgetState extends State<DemoRefreshListView>
    with SingleTickerProviderStateMixin {
  _DemoStateWidgetState();

  //ListView 数据源
  List list = new List();
  //ScrollController可以监听滑动事件，判断当前view所处的位置
  ScrollController _scrollController = ScrollController();
  //分页 加载的页数
  int _page = 1;
  //是否正在加载数据
  bool isLoading = false;
  @override
  void initState() {
    ///初始化，这个函数在生命周期中只调用一次
    super.initState();
    //初始化模拟数据
    list = List.generate(15, (i) => '哈喽,我是原始数据 $i');
    //设置监听
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print('滑动到了最底部');
        _getMore();
      }
    });
  }

  @override
  void didChangeDependencies() {
    ///在initState之后调 Called when a dependency of this [State] object changes.
    super.didChangeDependencies();
  }


  @override
  Widget build(BuildContext context) {
    return  new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text("list"),
      ),
      body: RefreshIndicator(
        //下拉刷新触发方法
        onRefresh: _onRefresh,
        //设置listView
        child: ListView.builder(
          //条目显示布局
          itemBuilder: _renderRow,
          //listView 的控制器
          controller: _scrollController,
          //条目个数据  这里+1 是最后一条目显示 加载更多提示
          itemCount: list.length+1,
        ),
      ),
    );
  }
  Widget _renderRow(BuildContext context, int index) {
    if (index < list.length) {
      return ListTile(
        title: Text(list[index]),
      );
    }
    return _getMoreWidget();
  }

  /**
   * 下拉刷新方法,为list重新赋值
   */
  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 1), () {
      print('refresh');
      setState(() {
        list = List.generate(20, (i) => '哈喽,我是新刷新的 $i');
      });
    });
  }
  /**
   * 上拉加载更多
   */
  Future _getMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });
      await Future.delayed(Duration(seconds: 1), () {
        print('加载更多');
        setState(() {
          list.addAll(List.generate(5, (i) => '第$_page次上拉来的数据'));
          _page++;
          isLoading = false;
        });
      });
    }
  }
  /**
   * 加载更多时显示的组件,给用户提示
   */
  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...     ',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(strokeWidth: 1.0,)
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _scrollController.dispose();
  }
}
